<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>VueStudyDemo</title>
</head>
<body>
<div id="app">
    <div><a href="index.html">返回首页</a></div><hr>
    <div>
        <div>mapGetters解构:</div>
        <div>doneTodos: {{doneTodos}}}</div>
        <div>doneTodosCount: {{doneTodosCount}}}</div>
    </div>
    <hr>
    <button @click = "clickMe">Get done todos</button>
    <div>doneTodos: {{bar}} | length:{{num}}</div>
    <div>
        <button @click="clickGetTodosById">Get todos by id 2</button>
        <div>{{bar2}}</div>
    </div>
</div>
<script src="https://vuejs.org/js/vue.js"></script>
<script src="https://unpkg.com/vuex@3.0.1/dist/vuex.js"></script>
<script>
    const store = new Vuex.Store({
        state: {
            todos: [
                { id: 1, text: '...', done: true },
                { id: 2, text: '...', done: false }
            ]
        },
        // 将getters看成store的计算属性，它跟计算属性一样依赖引用变量的变化，否则只会取缓存
        getters: {
            /* 属性风格访问 Property-Style Access */
            // state作为getter方法的第一个参数
            doneTodos: state => {
                return state.todos.filter(todo => todo.done)
            },
            // getter方法也可以有第二个参数，它是getters。用来引用其它getter方法
            doneTodosCount: (state, getters) => {
                return getters.doneTodos.length
            },
            /* 方法风格访问 Method-Style Access 返回一个方法的指针 此风格不缓存，每次调用时都会执行运算*/
            getTodosById: state => id => {
                return state.todos.find(todo => todo.id === id)
            }
        }
    })

    new Vue({
        el: '#app',
        //store
        store,
        // state
        data () {
            return {
                bar: null,
                bar2: null,
                num: 0
            }
        },
        computed: {
            // 使用解构赋值,解构解构，就是分解结构，或对象分解成单变量。mapGetters是Vuex的一个辅助函数，用于生成一个对象，或包含了一组对象的一个对象
            ...Vuex.mapGetters(['doneTodos', 'doneTodosCount'])
        },
        // actions
        methods: {
            clickMe() {
                this.bar = this.$store.getters.doneTodos
                this.num = this.$store.getters.doneTodosCount
            },
            clickGetTodosById() {
                this.bar2 = this.$store.getters.getTodosById(2)
            }
        }
    })
</script>
</body>
</html>